#include"Sock.hpp"

void *HandlerRequest(void *args)
{
    int sock = *(int *)args;
    delete (int *)args;
    pthread_detach(pthread_self());
    
    //1.读取请求
    char buffer[1024*10];
    memset(buffer, 0, sizeof(buffer));
    ssize_t s = recv(sock, buffer, sizeof(buffer)-1, 0);
    if(s > 0)
    {
        buffer[s] = 0;
        cout << buffer;

        //响应
        string response_str = "http/1.0 200 OK\n";
        response_str += "Content-Type: text/plain\n"; //text/plain,正文是普通的文本
        response_str += "\n"; //空行
        response_str += "hello yzy !!!!";//正文

        send(sock, response_str.c_str(), response_str.size(), 0);//作用等同于write
    }
    close(sock);
}


int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        cout << "Usage: \n\t" << argv[0] << " port" << endl;
        exit(1);
    }

    int listen_sock = Sock::Socket();
    Sock::Bind(listen_sock, atoi(argv[1]));
    Sock::Listen(listen_sock);
    for (;;)
    {
        int new_sock = Sock::Accept(listen_sock);
        if (new_sock >= 0)
        {
            int *pram = new int(new_sock);
            pthread_t tid;
            pthread_create(&tid, nullptr, HandlerRequest, (void *)pram);
        }
    }
}